package com.guapi.service;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class URLQueryFetcher implements QueryFetcher {
	
	/**
	 * Fetches a query using java.net.URL
	 * @param the ufull url of the query including the API key e.g. http://api.guardianapis.com/content/search?count=50&api_key=KEY
	 * @return a java.io.InputStream from the specified query
	 */
	public InputStream fetchQuery(String query) throws IOException {
		try {
				URL url = new URL(query);
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				connection.connect();
				int responseCode = connection.getResponseCode();
				if (responseCode != HttpURLConnection.HTTP_OK) {
					throw new IOException("Could not connect: " + responseCode + " : "  + connection.getResponseMessage());
				};
				return connection.getInputStream();
		} catch (MalformedURLException e) {
				throw new RuntimeException("MalformedUrl", e);
		}
	}
}
